package com.ljfiction.book.activitys;

import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.SearchView;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.google.gson.Gson;
import com.ljfiction.book.Baner.BiaoqianmoreBean;
import com.ljfiction.book.Dialog.LoadingDIalog;
import com.ljfiction.book.Dialog.NoBackgLodDialog;
import com.ljfiction.book.MyView.DBHelper;
import com.ljfiction.book.MyView.DividerItemDecoration;
import com.ljfiction.book.R;
import com.ljfiction.book.adapter.MoreBiaoqianAdapter;
import com.ljfiction.book.http.HttpManager;
import com.ljfiction.book.readview.Base;
import com.ljfiction.book.tools.StringTool;
import com.lzy.okhttputils.OkHttpUtils;
import com.lzy.okhttputils.callback.StringCallback;
import com.lzy.okhttputils.request.BaseRequest;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshLoadMoreListener;
import com.zhy.autolayout.utils.AutoUtils;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.Call;
import okhttp3.Response;

public class SearchOkActivity extends BaseActivity {

    @BindView(R.id.back_searchok)
    ImageView backSearchok;
    @BindView(R.id.searchokok)
    TextView searchokok;
    @BindView(R.id.recycle_searchok)
    RecyclerView recycleSearchok;
    @BindView(R.id.topbarsearchok)
    RelativeLayout topbarsearchok;
    @BindView(R.id.searchtextok)
    SearchView searchtextok;
    @BindView(R.id.reftesh_searchok)
    SmartRefreshLayout refteshSearchok;
    @BindView(R.id.nodata_search)
    LinearLayout nodataSearch;
    private List<BiaoqianmoreBean.DataBean.ListBean> booklist = new ArrayList<>();
    private BiaoqianmoreBean booklistBean;
    private BaseQuickAdapter adapter;
    private LoadingDIalog loadingDIalog;
    private int page = 1;
    private Context context;
    private DBHelper dbHelper;
    private NoBackgLodDialog noBackgLodDialog;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_search_ok);
        ButterKnife.bind(this);
        context = this;
        dbHelper = new DBHelper(this);
        toSearchview();
        searchtextok.onActionViewExpanded();
        searchtextok.setQuery(getIntent().getStringExtra("searchtext"), true);
        searchtextok.clearFocus();
        toRecycle();
    }

    private void toSearchview() {
        searchtextok.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
            @Override
            public boolean onQueryTextSubmit(String query) {
                if (StringTool.isEmpty(searchtextok.getQuery().toString())) {
                    showToast("搜索内容不能为空");
                    return false;
                }
                booklist.clear();
                page = 1;
                initData();
                searchtextok.clearFocus();
                return false;
            }

            @Override
            public boolean onQueryTextChange(String newText) {
                return false;
            }
        });
        if (searchtextok != null) {
            SearchView.SearchAutoComplete textView = searchtextok.findViewById(R.id.search_src_text);
            textView.setTextColor(Color.parseColor("#666666"));//字体颜色
            textView.setTextSize(12);//字体、提示字体大小
            textView.setHintTextColor(Color.parseColor("#999999"));//提示字体颜色
            try {        //--拿到字节码
                Class<?> argClass = searchtextok.getClass();
                //--指定某个私有属性,mSearchPlate是搜索框父布局的名字
                Field ownField = argClass.getDeclaredField("mSearchPlate");
                //--暴力反射,只有暴力反射才能拿到私有属性
                ownField.setAccessible(true);
                View mView = (View) ownField.get(searchtextok);
                //--设置背景
                mView.setBackgroundResource(R.drawable.search_shaoer);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    @OnClick({R.id.back_searchok, R.id.searchokok})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.back_searchok:
                goBack();
                break;
            case R.id.searchokok:
                if (StringTool.isEmpty(searchtextok.getQuery().toString())) {
                    showToast("搜索内容不能为空");
                    return;
                }
                dbHelper.insertHistory(searchtextok.getQuery().toString());
                booklist.clear();
                page = 1;
                initData();
                searchtextok.clearFocus();
                break;
        }
    }

    private void initData() {
        OkHttpUtils.post(HttpManager.IP + "/stacks-search")
                .params("keyWord", searchtextok.getQuery().toString().replaceAll(" ","").replaceAll("　",""))
                .params("startPage", String.valueOf(page))
                .params("isHotWorld", "1")
                .execute(new StringCallback() {
                    @Override
                    public void onBefore(BaseRequest request) {
                        super.onBefore(request);
                        if (noBackgLodDialog==null){
                            noBackgLodDialog=new NoBackgLodDialog(SearchOkActivity.this,true);
                        }
                        noBackgLodDialog.show();
                    }

                    @Override
                    public void onSuccess(String s, Call call, Response response) {
                        if (noBackgLodDialog!=null){
                            noBackgLodDialog.dismis();
                        }
                        Gson gson = new Gson();
                        refteshSearchok.finishLoadMore();
                        refteshSearchok.finishRefresh();
                        try {
                            booklistBean = gson.fromJson(s, BiaoqianmoreBean.class);
                            if (booklistBean.getReturnCode() == 200) {
                                booklist.addAll(booklistBean.getData().getList());
                                if (booklist.size()<1){
                                    nodataSearch.setVisibility(View.VISIBLE);
                                }else {
                                    nodataSearch.setVisibility(View.GONE);
                                    adapter.notifyDataSetChanged();
                                }

                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        }

                    }


                });
    }

    private void toRecycle() {
        recycleSearchok.setAdapter(adapter= new BaseQuickAdapter<BiaoqianmoreBean.DataBean.ListBean, BaseViewHolder>(R.layout.searchok_item,booklist) {
            @Override
            protected void convert(BaseViewHolder helper, BiaoqianmoreBean.DataBean.ListBean item) {
                AutoUtils.autoSize(helper.itemView);
                Glide.with(mContext).load(item.getBookImage()).into((ImageView) helper.getView(R.id.search_bookimage_morexiaobian));
                helper.setText(R.id.search_bookname_morexiaobian,item.getBookName())
                        .setText(R.id.search_clicknum_morexiaobian, StringTool.getClicknum(item.getClickTotal())+"点击")
                        .setText(R.id.search_writername_morexiaobian,"作者: "+item.getWriterName())
                        .setText(R.id.search_bookclassname_morexiaobian,item.getClassificationName())
                        .setText(R.id.search_bookcomment_morexiaobian,item.getBookIntroduction());
                (helper.getView(R.id.search_booklable_morexiaobian)).setVisibility(View.GONE);
                if(item.getBookStatus()==1){
                    helper.setText(R.id.search_zhuatai_morexiaobian,"已完结").setTextColor(R.id.search_zhuatai_morexiaobian, Color.parseColor("#FF6F00"));
                }else {
                    helper.setText(R.id.search_zhuatai_morexiaobian,"连载中").setTextColor(R.id.search_zhuatai_morexiaobian, Color.parseColor("#47B2D8"));
                }
                if (item.getBookAuthorization()==1||item.getBookAuthorization()==2){
                    helper.getView(R.id.searchpath).setVisibility(View.VISIBLE);
                }else {
                    helper.getView(R.id.searchpath).setVisibility(View.GONE);
                }
            }
        });
        recycleSearchok.setLayoutManager(new LinearLayoutManager(this));
        recycleSearchok.addItemDecoration(new DividerItemDecoration(this, DividerItemDecoration.VERTICAL_LIST));
        adapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                Intent intent = new Intent(SearchOkActivity.this, BookDetailsActivity.class);
                intent.putExtra("bookId", String.valueOf(booklist.get(position).getBookId()));
                startActivity(intent);
            }
        });
        refteshSearchok.setOnRefreshLoadMoreListener(new OnRefreshLoadMoreListener() {
            @Override
            public void onLoadMore(RefreshLayout refreshlayout) {
                if (booklistBean.getData().isIsLastPage()){
                    refreshlayout.finishLoadMore();
                    refreshlayout.setEnableLoadMore(false);
                }else {
                    page++;
                    initData();
                }

            }

            @Override
            public void onRefresh(RefreshLayout refreshlayout) {
                booklist.clear();
                page = 1;
                refreshlayout.setEnableLoadMore(true);
                initData();

            }
        });
    }

    @Override
    protected void onResume() {
        topbarsearchok.getBackground().setAlpha(255);
        super.onResume();
        searchokok.setFocusable(true);
        searchokok.setFocusableInTouchMode(true);
        searchokok.requestFocus();
    }
}


